<template>
  <div class="form_detail_page">
    <one-title :title="$route.query.id ? '工序库详情' : '工序库新增'"
               @refreshData="refresh"></one-title>
    <div v-loading="isLoading" class="fixed_top_56">
      <el-form ref="listForm" @submit.native.prevent :model="detailData" :rules="rules" v-if="!isEmpty&&!isLoading">
        <div class="from_content">
          <two-title title="基本信息"></two-title>
          <div class="from_panel">
            <div class="form_col form_col_left">
              <!--<el-form-item class="form_item" label="工厂名称:" prop="factoryId">
                <div class="input_wapper">
                  <el-select
                    v-model="detailData.factoryId"
                    size="small"
                    @change="factorySelect"
                    filterable
                    disabled
                    placeholder="">
                    <el-option
                      v-for="item in treeList"
                      :key="item.id"
                      :label="item.text"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <span class="analog_select">
                <i></i>
              </span>
                </div>
              </el-form-item>
              <el-form-item class="form_item" label="车间名称:" prop="workshopId">
                <div class="input_wapper">
                  <el-select
                    v-model="detailData.workshopId"
                    size="small"
                    @change="workshopSelect"
                    filterable
                    disabled
                    placeholder="">
                    <el-option
                      v-for="item1 in workshop"
                      :key="item1.id"
                      :label="item1.text"
                      :value="item1.id">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>-->
              <el-form-item class="form_item" label="工序编号:" prop="number">
                <div class="input_wapper">
                  <el-input
                    placeholder="请输入工序库编号"
                    :disabled="isDetail"
                    v-model.trim="detailData.number"
                    size="small"
                    clearable>
                  </el-input>
                </div>
              </el-form-item>
              <el-form-item class="form_item" label="工序名称:" prop="name">
                <div class="input_wapper">
                  <el-input
                    placeholder="请输入工种序库名称"
                    v-model.trim="detailData.name"
                    size="small"
                    clearable>
                  </el-input>
                </div>
              </el-form-item>
              <div class="form_item">
                <label></label>
                <div class="input_wapper mes_btn">
                  <el-button type="primary" native-type="submit" @click="save">保存</el-button>
                  <el-button @click="cancel">取消</el-button>
                </div>
              </div>
            </div>
            <div class="form_col">
              <el-form-item class="form_item" label="备注:" prop="remarks">
                <div class="input_wapper text_area">
                  <el-input type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入内容"
                            v-model="detailData.remarks"
                            maxlength="255"></el-input>
                  <span class="text_length">{{detailData.remarks ? detailData.remarks.length : 0}}/255</span>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <empty-page v-if="isEmpty&&!isLoading"></empty-page>
    </div>
  </div>
</template>

<script>
import TwoTitle from '@/components/TwoTitle'
import tree from '@/utils/dataParse.js'
import EmptyPage from '@/components/EmptyPage'

export default {
  name: 'processDatabaseDetail',
  data() {
    return {
      isLoading: true, //  加载中
      isChange: false, // 数据是否修改
      startWatch: false, // 是否开始监听页面数据变化 统一
      isEmpty: false, // 是否为空数据
      // 验证规则
      rules: {
        /*factoryId: [
          {required: true, message: '缺少工厂信息', trigger: 'blur'}
        ],
        workshopId: [
          {required: true, message: '缺少车间信息', trigger: 'blur'}
        ],*/
        name: [
          {required: true, message: '请输入工序名称', trigger: 'blur'},
        ],
        number: [
          {required: true, message: '请输入工序编号', trigger: 'blur'},
        ]
      }
    }
  },
  components: {
    TwoTitle,
    EmptyPage
  },
  computed: {
    // 详情页面数据
    detailData() {
      return this.$store.state.processDatabase.detailData
    },
    // 树形列表
    treeList() {
      return this.$store.state.treeList
    },
    // 工厂id
    factoryId() {
      return this.$store.state.userInfo.factoryId || ''
    },
    // 车间id
    workshopId() {
      return this.$store.state.userInfo.workshopId || ''
    },
    // 车间下拉选择列表
    workshop() {
      return tree.getChildren(this.treeList, this.detailData.factoryId)
    },
    saveState() {
      return this.$store.state.saveState
    },
    // 是否是详情页面
    isDetail() {
      return !!this.$route.query.id
    }
  },
  mounted() {
    this.refresh()
    this.setBaseInput()
  },
  methods: {
    // 详情页面初始化
    refresh() {
      this.isLoading = true
      this.startWatch = false
      Promise.all([this.getDetail(), this.getTreeList()]).then(() => {
        this.isLoading = false
      }).catch(() => {
        this.isLoading = false
      })
      this.setBaseInput()
    },
    // 工厂、车间赋值
    setBaseInput() {
      if (!this.$route.query.id) {
        this.detailData.factoryId = this.factoryId
        //this.detailData.workshopId = this.workshopId
      }
    },
    /**
     * 初始化——详情数据
     */
    getDetail() {
      let id = this.$route.query.id
      let postData = {
        method: 'get',
        url: 'a/workstagerepository/workstageRepository/get/' + id,
        module: 'processDatabase',
        state: 'detailData'
      }
      if (!id) {
        postData.clean = true
      }
      return this.$store.dispatch('saveData', postData).then((res) => {
        this.startWatch = true
        if (id && !res) {
          this.isEmpty = true
        }
      }).catch(() => {
        this.isEmpty = true
      })
    },
    /**
     * 初始化——树形结构数据
     */
    getTreeList() {
      return this.$store.dispatch('getTreeList')
    },
    // 工厂选择并重置相关子集
    factorySelect(value) {
      this.$store.dispatch('setFactoryValue', '')
    },
    // 车间选择并重置相关子集
    workshopSelect(value) {
      this.$store.dispatch('setFactoryValue', value)
    },
    // 保存数据
    save() {
      if (this.saveState === true) return
      this.$refs['listForm'].validate((valid) => {
        if (valid) {
          this.$store.commit('SetSaveState', true)
          this.detailData.viewSource = 100
          let postData = {
            method: 'post',
            url: 'a/workstagerepository/workstageRepository/save',
            module: 'processDatabase',
            data: this.detailData,
            noCommit: true
          }
          this.$store.dispatch('saveData', postData).then(() => {
            this.saveSuccess()
          }).catch(() => {
            this.$store.commit('SetSaveState', false)
          })
        }
      })
    },
    // 保存成功回调
    saveSuccess() {
      this.$message.success({
        message: '保存成功',
        duration: 500,
        center: true,
        onClose: () => {
          this.$store.commit('SetHasDetailChange', false) // 保存成功时需要将页面变化标记重置回false
          this.$store.dispatch('delCurrentViews', this.$route).then(() => {
            this.$store.commit('SetSaveState', false)
            this.$router.push('/processDatabase')
            this.$store.commit('SetRefresh', true)
          })
        }
      })
    },
    // 取消并关闭页面
    cancel() {
      this.backToList().then(() => {
        this.$store.dispatch('delCurrentViews', this.$route).then(() => {
          this.$router.push('/processDatabase')
        })
      })
    }
  },
  watch: {
    detailData: {
      // 当前页面数据变化总是会被监听到，我们只需要在我们想要开始监听startWatch的时候判断当前页面是否有变化
      handler() {
        if (this.startWatch) {
          this.$store.commit('SetHasDetailChange', true)
        } else {
          this.$store.commit('SetHasDetailChange', false)
        }
      },
      deep: true
    },
    factoryId: {
      handler() {
        this.setBaseInput()
      },
      deep: true
    }
  }
}
</script>

<style scoped lang="less">
</style>
